<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2022/3/31
 * Time: 10:44
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

namespace app\notify\controller;

use app\admin\model\BuddhaOrder;
use app\api\controller\v1\paymentApi;
use app\BaseController;
use think\facade\Log;

class Pay extends BaseController
{
    use paymentApi;

    /**
     * @return void
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     */
    public function notify()
    {
        $response = $this->payment_url->handlePaidNotify(function ($message, $fail) {

            //根据查询
            try {
                $order = (new BuddhaOrder())->getOrderByTradeNo($message['out_trade_no']);
            } catch (\Exception $e) {
                return $fail($e->getMessage());
            }
            if (empty($order)) {
                return $fail("订单不存在");
            }
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    $update_data = [
                        "payment" => 1,
                        "transaction_id" => $message['transaction_id'],
                        "payment_time" => time()
                    ];
                    $result = $order->save($update_data);

                    // 用户支付失败
                } elseif ($message['result_code'] === 'FAIL') {
                    $update_data = [
                        "payment" => 2,
                        "pay_time" => time()
                    ];
                    $result = $order->save($update_data);
                }
                if ($result) {
                    return true;
                } else {
                    return $fail("订单处理失败");
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
        });
        $response->send();
    }
}